package com.changgou.pay.service.impl;

import com.changgou.pay.service.WXPayService;
import com.github.wxpay.sdk.WXPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class WXPayServiceImpl implements WXPayService {
    @Autowired
    private WXPay wxPay;

    @Value("${wxpay.notify_url}")
    private String notify_url;

    //调用统一下单接口
    @Override
    public Map nativePay(String orderId, Integer money) {
        //1.封装请求参数
        try {
            Map<String, String> map = new HashMap<>();
            map.put("body", "畅购");
            map.put("out_trade_no", orderId);//存储订单id，本地系统自定生成的

            BigDecimal payMoney = new BigDecimal("0.01");//存储支付金额
            BigDecimal fen = payMoney.multiply(new BigDecimal("100"));//乘以一百换算成分
            fen = fen.setScale(0, BigDecimal.ROUND_UP);//向上取整不保留小数
            map.put("total_fee", String.valueOf(fen));
            map.put("spbill_create_ip", "127.0.0.1");//本机地址
            map.put("notify_url", notify_url);//支付成功后，微信给我们发送成功通知的地址
            map.put("trade_type", "NATIVE");//订单来源
            Map<String, String> result = wxPay.unifiedOrder(map); //微信发送回来的反馈信息
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    //根据id查询订单信息
    @Override
    public Map queeyOrder(String orderId) {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("out_trade_no", orderId);
            //主动调用微信的接口，查询我们生成的订单是否被支付
            Map<String, String> resultMap = wxPay.orderQuery(map);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
